const Hapi = require('@hapi/hapi');
const boom = require('@hapi/boom');
const inert = require('inert');
const vision = require('vision');
const Joi = require('joi');

const model = require('./model');
const plugin = require('./plugin');
const router = require('./router');
const config = require('./config.js');

const {log} = console;

const init = async () => {
  const server = Hapi.server({
    port: config.server.port,
    host: config.server.host,
    routes: {
      cors: {
        origin: ['*'],
      },
      files: {
        relativeTo: './public',
      },
      validate: {
        failAction(request, h, err) {
          return err;
        },
      },
    },
  });
  await server.state('paperId', {
    ttl: null,
    isSecure: false,
    isHttpOnly: false,
    encoding: 'base64json',
    clearInvalid: false,
    strictHeader: false,
  });

  server.decorate('server', 'Joi', Joi);
  server.decorate('server', 'headers', Joi.object({
    authorization: Joi.string().required(),
  }).unknown());
  server.decorate('toolkit', 'boom', boom);

  await server.register([
    inert,
    vision,
    plugin,
    model,
    router, // 加载路由
  ]);

  // 静态目录
  await server.route({
    method: 'GET',
    path: '/{param*}',
    handler: {
      directory: {
        path: '.',
      },
    },
    config: {
      auth: false,
    },
  });

  
  await server.start();
  log(`http://${config.server.host}:${config.server.port}/documentation`);
};
init();
